// 定义请求参数接口
interface FetchOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  headers?: { [key: string]: string };
  body?: any;
}

// 定义拦截器接口
interface Interceptor {
  request?: (options: FetchOptions) => FetchOptions;
  response?: (response: Response) => Response;
}

// 默认拦截器接口
const defaultInterceptors: Interceptor = {
  request: (options) => {
    // 添加或修改请求头
    // if (options.headers) {
    //   options.headers['Authorization'] = 'Bearer your-token-here';
    // }
    return options;
  },
  response: (response) => {
    // 处理响应数据，例如检查状态码
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response;
  },
};

// interface clentType {
//   options: FetchOptions;
//   interceptors?: Interceptor;
// }
/**
 * 使用fetch的封装函数，支持请求和响应拦截器
 */
const fetchClient = (options: FetchOptions, interceptors: Interceptor = defaultInterceptors): Promise<Response> => {
  // 请求拦截器
  if (interceptors.request) {
    options = interceptors.request(options);
  }

  // 执行fetch请求
  return fetch(options.url, {
    method: options.method,
    headers: options.headers,
    body: options.body ? JSON.stringify(options.body) : undefined,
  }).then((response) => {
    // 响应拦截器
    if (interceptors.response) {
      return interceptors.response(response);
    }
    return response;
  });
};

export default fetchClient;
export type { Interceptor, FetchOptions };

// 示例：使用封装的fetch函数
// const requestOptions: FetchOptions = {
//   url: 'https://api.example.com/data',
//   method: 'GET',
//   headers: {
//     'Content-Type': 'application/json',
//   },
// };

// fetchWithInterceptors(requestOptions, interceptors)
//   .then((response) => response.json())
//   .then((data) => console.log(data))
//   .catch((error) => console.error('Error:', error));
